package prototype;

import java.util.ArrayList;


public class Generator extends Switch {

    //minta amit ki kell adnia
    private ArrayList<Sign> pattern;

    //jelenleg hol tartunk a mintaban
    private int patternIndex;

    //konstruktor
    public Generator (String inPattern, int MaxOutputPort) throws Exception {
        super(MaxOutputPort);
        
        //Alap állapot
        patternIndex = 0;
        
        //Check valid pattern
        if (inPattern.equals("")) throw new Exception("Empty generator pattern!");//ErrorController.signalError("Empty generator pattern!");

        //check valid pattern
        for(int i = 0; i < inPattern.length(); i++){
            if( inPattern.charAt(i) != '0' ){
                if (inPattern.charAt(i) != '1')
                    //ErrorController.signalError("Invalid generator pattern!");
                    throw new Exception("Invalid generator pattern!");
            }
        }

        //pattern inicializalas
        pattern = new ArrayList<Sign>();

        //pattern betoltes
        for(int i = 0; i < inPattern.length(); i++){
            if(inPattern.charAt(i) == String.valueOf(1).charAt(0)){
                this.pattern.add(Sign.High);
            }
            else{
                this.pattern.add(Sign.Low);
            }
        }
    }

    //pattern meretet adja meg
    public int getSize() {return this.pattern.size();}

    //patternt ajda vissza
    public Sign getPattern(int index)
    {
        if(index<this.pattern.size())
            return this.pattern.get(index);
        else return Sign.Low;
    }

    //pattern indexet adja vissza
    public int getPatternIndex() {return this.patternIndex;}

    @Override
    //generator leptetese
    public void stepState () {     
        //pattern leptetese
        if(patternIndex == pattern.size() - 1)
            patternIndex = 0;
        else patternIndex++;
        
        //wirek updatelese
        for(int i = 0; i<outputList.size(); i++){
            for(Wire output : outputList.get(i)){
                output.setDigitalValue(pattern.get(patternIndex));
            }
        }
    }

    //generator reset
    public void reset () {
        //index nullara allitasa
        patternIndex = 0;

        //kimenetre adjuk a kezdoerteket
        for(int i = 0; i<outputList.size(); i++){
            for(Wire output : outputList.get(i)){
                output.setDigitalValue(pattern.get(patternIndex));
            }
        }
    }

    @Override
    public ElementType getType() {
        //tipus: generator
        return ElementType.Generator;
    }

}

